﻿using Interfaces.Model;
using Interfaces.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using Models;
using Services;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using WorkPieceDataCapture;
using WorkPieceDataCapture.ViewModels;

namespace ViewModels
{
    public class vm_WorkPieceDatacapture_RealTime : vm_Base, IWorkPieceDataCaptureViewModel
    {
        #region 全局变量与枚举
        WorkPieceDataCaptureRespository? respository;    //数据库操作类
        private IServiceProvider _serviceProvider;
        private MQTT_Client mqttClient;
        public ICommand RowSelectedCommand { get; set; }
        public ICommand OpenFile { get; set; }
        public ICommand PressureCurve { get; set; }
        WorkPieceDataCaptureHelper? Library;     //负责从PLC读数据的类
        private tb_WorkPieceDataCapture_Realtime? _dataModel_Newest;
        public tb_WorkPieceDataCapture_Realtime? dataModel_Newest    //最新保存的数据
        {
            get
            {
                return _dataModel_Newest;
            }
            set
            {
                _dataModel_Newest = value;
                OnPropertyChanged("dataModel_Newest");
            }
        }
        private tb_WorkPieceDataCapture_Realtime? _dataModel_Search;
        public tb_WorkPieceDataCapture_Realtime? dataModel_Search  //点击列表查看详情的缓存
        {
            get
            {
                return _dataModel_Search;
            }
            set
            {
                _dataModel_Search = value;
                OnPropertyChanged("dataModel_Search");
            }
        }
        public ObservableCollection<tb_WorkPieceDataCapture_Realtime> list_History { get; set; } //最近采集的历史
        public ObservableCollection<PointCheckRecord> list_History_PointCheck { get; set; } //最近采集的点检记录历史
        private ProduceSummary? _dataModel_Summary;    //呈现统计的实体类
        public ProduceSummary? dataModel_Summary
        {
            get
            {
                return _dataModel_Summary;
            }
            set
            {
                _dataModel_Summary = value;
                OnPropertyChanged("dataModel_Summary");
            }
        }

        private string _MQTTConnected;
        public string MQTTConnected
        {
            get { return _MQTTConnected; }
            set { _MQTTConnected = value; OnPropertyChanged("MQTTConnected"); }
        }   //MQTT连接状态

        Thread thread_Summary;  //刷新最新产量的线程
        bool switch_Summary = true;    //thread_Summary线程的开关
        #endregion
        #region 事件
        /// <summary>
        /// 构造函数
        /// </summary>
        public vm_WorkPieceDatacapture_RealTime(IServiceProvider serviceProvider, MQTT_Client mqtt)
        {
            this._serviceProvider = serviceProvider;
            this.mqttClient = mqtt;
            this.MQTTConnected = mqttClient.isConnected ? "连接正常" : "连接断开";
            this.respository = new WorkPieceDataCaptureRespository(this._serviceProvider);
            RowSelectedCommand = new RelayCommand(ProduceRecordselected);
            OpenFile = new RelayCommand(OpenFileByPath);
            PressureCurve = new RelayCommand(OpenPressureCurve);
            FuncResult<string> result = (FuncResult<string>)this.initialize();
        }
        //析构函数
        ~vm_WorkPieceDatacapture_RealTime()
        {

        }
        /// <summary>
        /// 类的初始化
        /// </summary>
        /// <returns></returns>
        public IFuncResult<string> initialize()
        {
            var result = new FuncResult<string>();
            try
            {
                dataModel_Newest = new tb_WorkPieceDataCapture_Realtime();
                dataModel_Search = new tb_WorkPieceDataCapture_Realtime();
                list_History = new ObservableCollection<tb_WorkPieceDataCapture_Realtime>();
                list_History_PointCheck = new ObservableCollection<PointCheckRecord>();
                dataModel_Summary = new ProduceSummary();
                Library = new WorkPieceDataCaptureHelper(_serviceProvider, mqttClient);
                Library.evt_FeedingNewestData += this.getNewestSavedData;
                Library.evt_FeedingNewestPointCheckData += this.getNewestPointCheckData;
                thread_Summary = new Thread(this.getNewestProduceSummary);
                thread_Summary.IsBackground = true;
                thread_Summary.Start();
                result = getTodayRealTimeData();
                result.bSuccess = true;
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }
        /// <summary>
        /// 从Helper获取到最新保存的数据的处理
        /// </summary>
        /// <param name="model"></param>
        public void getNewestSavedData(IDataModel model)
        {
            try
            {
                if (model != null)
                {
                    this.dataModel_Newest = model as tb_WorkPieceDataCapture_Realtime;
                    Application.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        this.list_History.Insert(0, model as tb_WorkPieceDataCapture_Realtime);
                        if (list_History.Count >= 500)
                        {
                            list_History.RemoveAt(499);
                        }
                        this.MQTTConnected = mqttClient.isConnected ? "连接正常" : "连接断开";
                    }));
                }
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 从Helper获取到最新保存的点检数据的处理
        /// </summary>
        /// <param name="model"></param>
        public void getNewestPointCheckData(PointCheckRecord model)
        {
            try
            {
                if (model != null)
                {
                    Application.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        this.list_History_PointCheck.Insert(0, model);
                        if (list_History_PointCheck.Count >= 500)
                        {
                            list_History_PointCheck.RemoveAt(499);
                        }
                    }));
                }
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 在生产记录选中行查看明细的事件处理
        /// </summary>
        /// <param name="parameter"></param>
        private void ProduceRecordselected(object parameter)
        {
            // 这里处理选中行的逻辑
            // 参数 parameter 可以是 DataGridRow 或选中项的数据对象，取决于您如何设置 CommandParameter
            string aaa = "";
            var model = parameter as tb_WorkPieceDataCapture_Realtime;
            if (model != null)
            {
                this.dataModel_Search = model;
            }
        }
        /// <summary>
        /// 打开相机路径
        /// </summary>
        /// <param name="parameter"></param>
        private void OpenFileByPath(object objPath)
        {
            var result = GlobalClass.openFile(objPath.ToString());
            if (!result.bSuccess)
            {
                MessageBox.Show(result.strMsg);
            }
        }

        /// <summary>
        /// 打开压力曲线图
        /// </summary>
        /// <param name="parameter"></param>
        private void OpenPressureCurve(object type)
        {
            switch (type.ToString())
            {
                case "Newest":
                    // 打开图表窗口
                    var chartWindow_Newest = new WorkPieceDataCapture.Views.CoordinateChartWindow(_dataModel_Newest);
                    chartWindow_Newest.ShowDialog();
                    break;
                case "Search":
                    var chartWindow_Search = new WorkPieceDataCapture.Views.CoordinateChartWindow(_dataModel_Search);
                    chartWindow_Search.ShowDialog();
                    break;
            }
        }
        #endregion
        #region 方法
        /// <summary>
        /// 获取产量报表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private void getNewestProduceSummary()
        {
            while (switch_Summary)
            {
                try
                {
                    var result_summary = respository.getProduceSummary();
                    if (result_summary.bSuccess == true)
                    {
                        this.dataModel_Summary = result_summary.obj_Return as ProduceSummary;
                    }
                    else
                    {
                        this.dataModel_Summary = new ProduceSummary();
                        this.dataModel_Summary.OKRateToday = "Error";
                        this.dataModel_Summary.OKRate24Hour = "Error";
                    }
                }
                catch (Exception ex)
                {
                }
                Thread.Sleep(5000);
            }
        }
        private FuncResult<string> getTodayRealTimeData()
        {
            var result = new FuncResult<string>();
            try
            {
                var context = this._serviceProvider.GetService<AppDbContext>();
                var conditions = new model_SearchCondition();
                conditions.dDate_Begin = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                conditions.dDate_End = DateTime.Now;
                var result_today = respository.SearchDataFromRealTimeTable(conditions, context.tb_workpiecedatacapture_realtime);
                if (result_today.bSuccess && result_today.obj_Return.Count > 0)
                {
                    result_today.obj_Return = result_today.obj_Return.OrderByDescending(x => x.dDate).ToList();
                    this.list_History = new ObservableCollection<tb_WorkPieceDataCapture_Realtime>(result_today.obj_Return);
                    this.dataModel_Newest = this.list_History[0];
                    result.bSuccess = true;
                }
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }
        #endregion
    }
}